import { Component, OnInit, ViewChild, OnDestroy, AfterContentInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NzMessageService, UploadFile, NzModalService, NzNotificationService } from 'ng-zorro-antd';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { ActivatedRoute, Router } from '@angular/router';
import {SettingsService, TitleService} from '@delon/theme';
import { Constant, ServiceResult } from '@core/constant';
import { maService } from '../../../../service/ma/ma.service';
import { EmitterService } from 'app/service/emit.service';
import { CommService } from '../../../../service/comm/comm.service';
import {insService} from "../../../../service/ins/ins.service";
import {ProductService} from "../../../../service/prod/product.service";
import {fileService} from "../../../../service/file/file.service";

@Component({
  selector: 'file-view-editto',
  templateUrl: './file-editto.component.html',
  styleUrls: ['./file-editto.component.less']
})
export class fileViewEdittoComponent implements OnInit, OnDestroy {
  product:  any = {
    id:null,
    fileNo: null,
    bpmStatus:null,
    fileName: null,
    fileStatus: null,
    fileOwner: null,
    fileNowOwner: null /*No show*/,
    fileFrom: null,
    fileTo: null,
    fileRemark: null
  };
  bpmStatus =  [{text: '我的', value: '1'}, {text: '已发送', value: '10'}, {text: '已接收', value: '20'}];

  MAX_COUNT = 60;
  tabIndex = 0;
  saleing = false;
  private sub: any;

  // 预览图片对象
  previewImage = '';
  // 是否可以预览
  previewVisible = false;

  uploadUrl = '';
  avatarParam = { sbtype: 'No',  filetype:'file',orderNo: 'no'};
  fileList = [ ];
  avatarUrl:string;
  loading = false;
  sysusers=[];

  constructor(
    private productService: ProductService,

    public setting: SettingsService,
    private msg: NzMessageService,
    private modalService: NzModalService,
    private fileService: fileService,
    private emit: EmitterService,
    private notification: NzNotificationService,
    private route: ActivatedRoute,
    private titleService: TitleService,
    private cnt: Constant,
    private router: Router,
    private comm: CommService
  ) {}

  ngOnInit(): void {
    this.loadsysusers();

    // this.loadbpmStatus();

    this.uploadUrl = this.fileService.uploadUrl();

    // 获取参数
    this.sub = this.route.params.subscribe(params => {
      this.product.id = params["id"]
      console.log("this.product.id****************"+this.product.id);
      // 获取商品详情
      this.getProductInfo();
      // this.getfileList(this.product.id);

    });
    // 隐藏reusetab
    setTimeout(() => {
      this.emit.sendMessage("HIDE_REUSE_TAB");
    }, 1000);
  }

  // 显示reusetab
  ngOnDestroy() {
    this.emit.sendMessage("SHOW_REUSE_TAB");
  }

  changeTab(index) {
    // 使用异步的方式更新组件, 防止ngIf错误
    Promise.resolve(null).then(() => this.tabIndex = index);
  }



  getProductInfo() {
    this.fileService.getfile(this.product.id).pipe(
      catchError(err => {
        return of(err);
      })
    ).subscribe(data => {
      this.product = data.data;
      this.product.fileStatus="已接收";

      this.avatarParam = { sbtype: 'No',  filetype:'file',orderNo: this.product.fileNo};
      this.titleService.setTitle("编辑");
      if (data.data.fxjFileListList.length > 0) {
        let flag = 0;
        for (const detail of data.data.fxjFileListList) {
          this.fileList.push( {
            uid: detail.id,
            name: detail.fileName,
            status: 'done',
            url: detail.fileUrl
          } )
          flag++;
        }
      };
    })
  }

  back() {
    this.router.navigate(['/file/file']);
  }

  save() {

    let fxjFileMainPage = {
      updateBy:this.setting.user.username,
      id:this.product.id,
      bpmStatus:"20",
      fileNo: this.product.fileNo,
      fileName: this.product.fileName,
      fileStatus: this.product.fileStatus,
      fileOwner: this.product.fileOwner,
      fileNowOwner: this.product.fileNowOwner, /*No show*/
      fileFrom: this.product.fileFrom,
      fileTo: this.product.fileTo,
      fileRemark: this.product.fileRemark
      // fiOperDate: this.product.fiOperDate /*No show*/
    };

    // 调用接口
    this.fileService.editfile(fxjFileMainPage).pipe(
      catchError(err => {
        return of(err);
      })
    ).subscribe(data => {
      if (data.ok === true) {
        this.msg.success('修改成功');
        this.emit.sendMessage("RELOAD_GOODS_LIST");
      } else {
        this.msg.error(data['message']);
      }
    })
  }

  changeColor(res) {
    this.product.colorSort = res.color.hex;
  }

  beforeUpload = (file: File) => {
    const isJPG = file.type === 'image/jpeg';
    const isPNG = file.type === 'image/png';
    if (!isJPG && !isPNG) {
      this.msg.warning(`不支持的格式: ${file.type}`);
    }
    const isLt2M = file.size / 1024 / 1024 < 10;
    if (!isLt2M) {
      this.msg.warning('图片不能超过2MB!');
    }
    return (isJPG || isPNG) && isLt2M;
  }

  private getBase64(img: File, callback: (img: any) => void) {
    if (img) {
      const reader = new FileReader();
      reader.addEventListener('load', () => callback(reader.result));
      reader.readAsDataURL(img);
    }
  }
  // 加载证件类型
  loadsysusers() {
    this.sysusers = [];
    this.comm.getsysusers(this.setting.user.sysorgCode).subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
        for (const row of ret['data']) {
          this.sysusers.push({ text: row.typename, value: row.typecode });
        }
      }
    })
  }
  handleChange(info: { file: UploadFile }) {
    if (info.file.status === 'uploading') {
      this.loading = true;
      return;
    }
    if (info.file.status === 'done') {
      this.getBase64(info.file.originFileObj, (img: any) => {
        this.loading = false;
        this.avatarUrl = img;

      });
    }
    if (info.file.status === 'error') {
      this.msg.error(info.file.error.error);
    }
  }

  handlePreview = (file: UploadFile) => {
    this.previewImage = file.url || file.thumbUrl;
    this.previewVisible = true;
  }
}
